package com.example.androidkt.fourth

import android.content.Context
import android.media.AsyncPlayer
import android.media.MediaPlayer
import android.os.SystemClock
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlin.concurrent.thread
import kotlin.math.log

class LifecycleObject1(private val owner: LifecycleOwner) : LifecycleObserver {

    val TAG = this.javaClass.simpleName
    private lateinit var player: MediaPlayer

    init {
        owner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        player = MediaPlayer()
        Log.d(TAG, "player     ->     onCreate")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onResume() {
        thread {
            SystemClock.sleep(5000)
            if (owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                player.start()
                Log.d(TAG, "player     ->     onResume")
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        player.stop()
        Log.d(TAG, "player     ->     onPause")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestory() {
        player.release()
        Log.d(TAG, "player     ->     onDestory")
    }
}

class LifecycleObject {

    val TAG = this.javaClass.simpleName
    private lateinit var player: MediaPlayer


    fun onCreate() {
        player = MediaPlayer()
        Log.d(TAG, "player     ->     onCreate")
    }

    fun onResume() {
//        SystemClock.sleep(3000)
        player.start()
        Log.d(TAG, "player     ->     onResume")
    }

    fun onPause() {
        player.stop()
        Log.d(TAG, "player     ->     onPause")
    }

    fun onDestory() {
        player.release()
        Log.d(TAG, "player     ->     onDestory")
    }
}

class LifecycleObject3(private val owner: LifecycleOwner) : LifecycleEventObserver {

    val TAG = this.javaClass.simpleName
    private lateinit var player: MediaPlayer

    init {
        owner.lifecycle.addObserver(this)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event){
            Lifecycle.Event.ON_CREATE ->{}
            Lifecycle.Event.ON_RESUME ->{}
            else -> {}
        }
    }

    fun onCreate() {
        player = MediaPlayer()
        Log.d(TAG, "player     ->     onCreate")
    }

    fun onResume() {
//        SystemClock.sleep(3000)
        player.start()
        Log.d(TAG, "player     ->     onResume")
    }

    fun onPause() {
        player.stop()
        Log.d(TAG, "player     ->     onPause")
    }

    fun onDestory() {
        player.release()
        Log.d(TAG, "player     ->     onDestory")
    }


}
